<template>
  <div class="categorymanagement-container">
    <el-input v-model="input" style="width: 20%; margin-right: 20px; margin-bottom: 20px" placeholder="类目名称"></el-input>
    <el-button type="primary" icon="el-icon-search" @click="seachByName">查询</el-button>
    <el-button type="primary" @click="addCategoryOption('One')">添加一级类目</el-button>
    <!-- 类目表格 -->
    <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#EDF4FF', color: '#606266' }">
      <el-table-column prop="id" label="编号" width="180"> </el-table-column>
      <el-table-column prop="name" label="名称" width="180"> </el-table-column>
      <el-table-column prop="level" label="级别" width="180"> </el-table-column>
      <el-table-column prop="sort" label="排序" width="180"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button size="small" type="primary" icon="el-icon-edit-outline"
            @click="addCategoryOption('editOne', row)"></el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addCategoryOption('Two', row)"></el-button>
          <el-button size="small" type="primary" @click="seachCategorySecond(row.id)">查看二级类目</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" @click="deletCategory(row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 类目表格 -->
    <!-- 分页 -->
    <el-row type="flex" justify="start">
      <!-- <span>Total: {{ 20 }}</span> -->
      <el-pagination background layout="total ,prev, pager, next" :total="total" :page-size="page.pagesize"
        :current-page="page.page" @current-change="changePage">
      </el-pagination>
    </el-row>
    <!-- /分页 -->
    <!-- 弹层组件 -->
    <!-- 查看二级类目弹层 -->
    <el-dialog title="查看二级类目" :visible.sync="dialogVisible" width="55%" :before-close="handleCloseOne">
      <el-table :data="oneData" style="width: 100%" :header-cell-style="{ background: '#EDF4FF', color: '#606266' }">
        <el-table-column prop="id" label="编号" width="110"> </el-table-column>
        <el-table-column prop="name" label="名称" width="130">
        </el-table-column>
        <el-table-column prop="level" label="级别" width="110">
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="110">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button size="small" type="primary" icon="el-icon-edit-outline"
              @click="addCategoryOption('editTwo', row)"></el-button>
            <el-button size="small" type="danger" icon="el-icon-delete"
              @click="deletCategory(row.id, row.parentId)"></el-button>
          </template>
          <!--点击删除显示弹框  -->
          <!-- <el-popover placement="bottom" width="160" v-model="visibleNF">
            <p>这是一段内容这是一段内容确定删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text">取消</el-button>
              <el-button type="primary" size="mini" @click="del"
                >确定</el-button
              >
            </div>
            <el-button
              slot="reference"
              size="small"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
          </el-popover> -->
          <!--/点击删除显示弹框  -->
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- /查看二级类目弹层 -->
    <!-- 编辑弹框(新增类目共用) -->
    <el-dialog :title="title" :visible.sync="dialogVisible_edit" width="30%" :before-close="handleClose">
      <el-form ref="setEditForm" label-width="60px" :model="editdata" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editdata.name" style="width: 80%" placeholder="请输入名称" maxlength="10"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="editdata.sort" style="width: 80%" placeholder="请输入排序"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /编辑弹框 -->
  </div>
</template>

<script>
import {
  seachCategory,
  seachCategoryOption,
  deletCategory,
  addCategory,
  updateCategory,
} from "@/api/allstatas";
import store from "@/store";
export default {
  name: "",
  components: {},
  data() {
    // 查看是否有相同名称的类目
    const checkNameRepeat = async (rule, value, callback) => {
      const res = await seachCategory(this.datas); //查看一级类目
      let isRepeat = false;
      if (!this.editdata.id) {
        isRepeat = res
          .filter((item) => item.name === this.editdata.name)
          .some((item) => item.name === value);
      }
      isRepeat
        ? callback(new Error(`已经存在*${value}*这个类目了`))
        : callback();
    };
    // 查看同一个一级类目下是否有相同的二级类目
    const checkSortRepeat = async (rule, value, callback) => {
      const res = await seachCategory(this.datas); //查看一级类目
      let isRepeat = false;
      if (!this.editdata.id) {
        isRepeat = res
          .filter((item) => item.sort === this.editdata.sort)
          .some((item) => item.sort === value);
      }

      isRepeat ? callback(new Error(`排序*${value}*已经存在了`)) : callback();
    };
    return {
      input: "",
      //   数据长度
      total: 0,
      title: "",
      // 分页
      page: {
        page: 1,
        pagesize: 10,
      },
      //  获取数据
      datas: {
        name: "",
        parentId: "",
        sid: store.getters.sid,
      },
      // 编辑数据
      editdata: {
        id: "",
        name: "",
        parentId: "",
        level: "",
        sort: "",
        sid: Number(store.getters.sid),
      },
      // 二级类目弹层的显示
      dialogVisible: false,
      dialogVisible_edit: false,
      //   二级弹层删除弹框
      //   visibleNF: false,
      //  表格数据
      tableData: [],
      //   保存二级类目
      oneData: [],
      //   当点击查看二级时，保存此时的一级id，在删除二级类目时，需要传这个id作为parentId
      firstidToSecondpid: "",
      //   编辑已经增加类目操作的规则
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { validator: checkNameRepeat, trigger: "blur" },
        ],
        sort: [
          { required: true, message: "请输入排序", trigger: "blur" },
          { validator: checkSortRepeat, trigger: "blur" },
        ],
      },
    };
  },
  computed: {},
  created() {
    this.seachCategory();
  },
  methods: {
    // 点击删除测试
    // del() {
    //   console.log("点击确认删除");
    //   this.visibleNF = false;
    //   console.log(this.visibleNF);
    // },
    // 查询商品类目(一级)
    async seachCategory() {
      this.datas.parentId = 1;
      const res = await seachCategory(this.datas);
      //   console.log(res);
      this.total = res.length;
      this.tableData = res;
      //   执行完了清除数据
      this.datas.parentId = "";
    },
    // 单独查询二级
    async seachCategorySecond(id) {
      this.dialogVisible = true;
      this.datas.parentId = id;
      //   将此时的一级id保存着
      this.firstidToSecondpid = id;
      const res = await seachCategory(this.datas);
      this.oneData = res;
    },
    // 根据类目名称查询
    async seachByName() {
      this.datas.name = await this.input;
      await this.seachCategory();
      //查询完清除datas中数据(name直接输入框删除)
      this.datas.parentId = "";
    },
    // 添加类目设置
    addCategoryOption(option, row) {
      if (option === "One") {
        this.title = "添加一级类目";
        this.editdata.parentId = 1;
        this.editdata.level = 1;
      } else if (option === "editOne") {
        this.title = "编辑一级类目";
        this.editdata.name = row.name;
        this.editdata.sort = row.sort;
        this.editdata.id = row.id;
        // 编辑的时候不需要level这里是为了方便后面区分是操作的哪一级
        this.editdata.level = 1;
      } else if (option === "Two") {
        this.title = "添加二级类目";
        this.editdata.parentId = row.id;
        this.editdata.level = 2;
      } else if (option === "editTwo") {
        this.title = "编辑二级类目";
        this.editdata.name = row.name;
        this.editdata.sort = row.sort;
        this.editdata.id = row.id;
        // 作用与上同理
        this.editdata.level = 2;
      }
      this.dialogVisible_edit = true;
    },
    // 添加类目(和编辑)
    async addCategory() {
      try {
        this.$refs.setEditForm.validate(async (isok) => {
          if (isok) {
            if (this.editdata.id) {
              await updateCategory(this.editdata);
            } else {
              await addCategory(this.editdata);
            }
            //关闭弹层重新拉取数据
            this.dialogVisible_edit = false;
            if (this.editdata.level === 1) {
              // 编辑的是一级类目，只需要刷新一级
              this.seachCategory();
            }

            if (this.editdata.id && this.editdata.level == 2) {
              // 重新拉取二级目录数据
              this.datas.parentId = this.firstidToSecondpid;
              this.oneData = await seachCategory(this.datas);
            }
            (this.editdata = {
              id: "",
              name: "",
              parentId: "",
              level: "",
              sort: "",
              sid: Number(store.getters.sid),
            }),
              this.$message.success("操作成功");
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 取消编辑或新增类目
    btnCancel() {
      (this.editdata = {
        id: "",
        name: "",
        parentId: "",
        level: "",
        sort: "",
        sid: Number(store.getters.sid),
      }),
        (this.firstidToSecondpid = "");
      this.$refs.setEditForm.resetFields(); //重置关键校验字段
      this.dialogVisible_edit = false;
    },
    // 查询商品类目选项
    async seachCategoryOption(id) {
      this.dialogVisible = true;
      const res = await seachCategoryOption();
      let oneDatachilden = res.filter((item) => {
        return item.value === id;
      });
      this.oneData = oneDatachilden[0].children;
    },
    // 删除
    async deletCategory(id, parentId) {
      try {
        await this.$confirm("确定要删除吗?删除后数据不可恢复！！！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await deletCategory(id);
        this.seachCategory(); //删除后重新拉取数据
        // 重新拉取二级数据
        if (this.firstidToSecondpid) {
          // 进入表示删除的是二级类目
          this.seachCategorySecond(this.firstidToSecondpid);
        }
        this.$message.success("删除成功");
      } catch (error) {
        // console.log(error);
      }
    },
    // 二级类目弹层关闭时需要执行的操作
    handleCloseOne(done) {
      this.$confirm("确认关闭?")
        .then((_) => {
          this.dialogVisible = false
          done();
        })
        .catch((_) => { });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.btnCancel();
          done();
        })
        .catch((_) => { });
    },
    // 分页
    changePage(newPage) {
      // newPage当前点击的页码
      console.log(newPage);
    },
  },
};
</script>

<style lang="scss" scoped>
.categorymanagement-container {
  height: 100%;
}
</style>